import requests
import threading
import bs4
import os

header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) \
                        AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'}


def get_pic_urls(url):

    pic_adds = []
    req = requests.get(url,headers=header)
    page = req.text

    soup = bs4.BeautifulSoup(page, 'lxml')
    soup_img = soup.find_all('img', class_='pic')

    for img in soup_img:
        raw_url = img['src']
        pic_url = 'http://ssyer.com'+raw_url
        pic_adds.append(pic_url)


    return pic_adds


def download_pic(url):

    req = requests.get(url)
    content = req.content
    name = url.split('/')[-1]
    with open(name, 'wb')as f:
        f.write(content)


def main():

    url = 'http://ssyer.com/index_page_{}.html'

    for i in range(1,3):
        print('正在下载第 {} 页图片'.format(i))
        p_url = url.format(i)
        pic_urls = get_pic_urls(p_url)

        # 多线程
        threads = []
        for i in pic_urls:
            t = threading.Thread(target=download_pic,args=(i,))
            threads.append(t)

        for i in threads:
            i.start()


if __name__ == '__main__':
    main()
